import threading
import time
import random

# 全局变量与锁
current_water = 0.0
stop_flag = False
lock = threading.Lock()  # 确保变量操作的线程安全

# 用户输入目标水量（复用之前修正的代码）
water_set = input("输入你希望装载的水量（单位：毫升）或按回车默认 150：")
if water_set.strip() == "":
    water_set = 150
else:
    try:
        water_set = int(water_set)
        if water_set <= 0:
            print("输入值需大于 0，已重置为默认值 150")
            water_set = 150
    except ValueError:
        print("输入无效，已使用默认值 150")
        water_set = 150
print(f"最终水量设定为：{water_set} 毫升")


# 输入监听线程
def input_listener():
    global stop_flag
    input("按回车键停止出水...")  # 简化交互，直接等待回车
    with lock:
        stop_flag = True


# 启动监听线程
input_thread = threading.Thread(target=input_listener)
input_thread.daemon = True
input_thread.start()

# 主循环
print("正在出水中...")
try:
    while True:
        with lock:
            if stop_flag or current_water >= water_set:
                break

        # 模拟水量增加
        increment = round(random.uniform(3, 5), 2)
        with lock:
            current_water = round(current_water + increment, 2)

        print(f"水量增加 {increment}，当前水量: {current_water:.2f}，目标水量 {water_set}")
        time.sleep(0.25)
except KeyboardInterrupt:
    with lock:
        stop_flag = True

# 最终结果
print(f"感谢使用，总共出水量: {current_water:.2f} 毫升")